package com.yjd.pub.asynmsg.service;

import com.yjd.comm.asynmsg.enums.TaskMsgClientIdEnum;
import com.yjd.comm.asynmsg.enums.TaskMsgTypeEnum;
import com.yjd.comm.asynmsg.model.TaskMsgModel;
import com.yjd.comm.asynmsg.service.ITaskMsgService;
import com.yjd.comm.asynmsg.util.AsynMsgUtil;
import com.yjd.comm.base.dao.IBaseDao;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.base.service.impl.BaseServiceImpl;
import com.yjd.comm.util.FrameUtil;
import com.yjd.pub.asynmsg.dao.ITaskMsgDao;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * <b>description</b>：任务消息业务实现<br>
 * <b>time</b>：2015-01-26 18:47:03 <br>
 * <b>author</b>： ready likun_557@163.com
 */
@Service("taskMsgService")
public class TaskMsgServiceImpl extends BaseServiceImpl implements ITaskMsgService {

	/**
	 * 新增一条任务消息
	 * 
	 * @param ref_id
	 * @param msgTypeEnum
	 * @return
	 * @throws Exception
	 */
	public TaskMsgModel insert(String ref_id, TaskMsgTypeEnum msgTypeEnum, TaskMsgClientIdEnum client_id, String client_order_id) throws Exception {
		return this.insert(ref_id, msgTypeEnum, null, client_id, client_order_id);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public TaskMsgModel insert(String ref_id, TaskMsgTypeEnum msgTypeEnum, Map extend_data_map, TaskMsgClientIdEnum client_id, String client_order_id) throws Exception {
		TaskMsgModel taskMsgModel = AsynMsgUtil.buidTaskMsgModel(ref_id, msgTypeEnum, extend_data_map, client_id, client_order_id);
		return this.taskMsgDao.insertTaskMsg(taskMsgModel, DbWREnums.WRITE.isWrite());
	}

	
	
	public void inserts(List<TaskMsgModel> models) throws Exception{
		this.taskMsgDao.insertBatch(models, DbWREnums.WRITE.isWrite());
	}

	/**
	 * 更新
	 * 
	 * @param model
	 * @return
	 * @throws Exception
	 */
	public int updateTaskMsg(TaskMsgModel model) throws Exception {
		return this.taskMsgDao.updateTaskMsg(model, DbWREnums.WRITE.isWrite());
	}

	/**
	 * 将任务消息移到日志表中
	 * 
	 * @param task_msg_ids
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public void moveTaskMsgToTaskMsgLog(List<Long> task_msg_ids) throws Exception {
		if (task_msg_ids != null) {
			for (Long task_msg_id : task_msg_ids) {
				if (task_msg_id != null) {
					// 最后留一条，避免mysql重启之后自增从1开始
					if (this.taskMsgDao.getModelListCount(FrameUtil.newHashMap("gt_id", task_msg_id), DbWREnums.WRITE.isWrite()) > 0) {
						TaskMsgModel taskMsgModel = this.taskMsgDao.getModelById(task_msg_id, DbWREnums.WRITE.isWrite());
						if (taskMsgModel != null) {
							this.taskMsgDao.deleteTaskMsg(FrameUtil.newHashMap("id", task_msg_id), DbWREnums.WRITE.isWrite());
							this.taskMsgDao.insertTaskMsgLog(taskMsgModel, DbWREnums.WRITE.isWrite());
						}
					}
				}
			}
		}
	}

	@Resource
	private ITaskMsgDao taskMsgDao;

	@Override
	public IBaseDao getBaseDao() {
		return this.taskMsgDao;
	}

}
